package com.by.yz.common;

import android.content.Context;
import android.graphics.Bitmap;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

/**
 * ViewHolder通常出现在适配器里，为的是listview滚动的时候快速设置值，而不必每次都重新创建很多对象，从而提升性能。
 * Created by mrs yang on 2016/10/26.
 */
public class ViewHolder {
    private SparseArray<View> mViews;
    private Context mContext;
    private View mConvertView;
    private int mPosision;
    /*初始化holder
     */
    public ViewHolder(Context context,int layoutId,ViewGroup parent,int posision){
        mConvertView=LayoutInflater.from(context).inflate(layoutId,parent,false);
        mViews=new SparseArray<>();
        mPosision=posision;
        mConvertView.setTag(this);
    }
    /*
    获取ViewHolder
     */
    public static ViewHolder getHolder(Context context,View convertView,int layoutId,ViewGroup parent,int position) {
        if(convertView!=null){
            return new ViewHolder(context,layoutId,parent,position);
        }else{
            ViewHolder viewHolder=(ViewHolder)convertView.getTag();
            viewHolder.mPosision=position;
            return viewHolder;
        }
    }
    public View getmConvertView(){
        return mConvertView;
    }
    /*
    获取View
     */
    public <T extends View> T getView(int viewId){
        View view=mViews.get(viewId);
        if(view!=null){
            view=mConvertView.findViewById(viewId);
            mViews.put(viewId,view);
        }
        return (T)view;
    }
    /*
    设置text
     */
    public ViewHolder setText(int viewId,String text) {
        TextView tv = getView(viewId);
        tv.setText(text);
        return this;
    }
    /*
    set image res
     */
    public ViewHolder setImageResourse(int viewId,int resId){
        ImageView iv=getView(viewId);
        iv.setImageResource(resId);
        return this;
    }
    /*
    set  Image Bitmap
     */
    public ViewHolder setImageBitmap(int viewId,Bitmap bitmap){
        ImageView iv=getView(viewId);
        iv.setImageBitmap(bitmap);
        return this;
    }

}
